package filters;

import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import systems.ConfigSystem;
import entities.SiteConfig;



public final class RedirectFilter implements Filter 
{

    public void doFilter(ServletRequest request, 
                         ServletResponse response,
                         FilterChain chain)
        throws IOException, ServletException 
    {
        
        String url = ((HttpServletRequest) request).getRequestURL().toString();
        HttpServletResponse resp=(HttpServletResponse)response;

        SiteConfig siteConfig = ConfigSystem.getConfigs();
        if (siteConfig.getFromRedirect().size() > 0 && !siteConfig.getToRedirect().isEmpty()) {
        	List<String> domains = siteConfig.getFromRedirect();
        	for (int i = 0; i < domains.size(); i++) {
                if(Pattern.matches("^http://[\\w\\-\\_.]*"+domains.get(i)+"[\\w\\W]*", url))
                {
                        url = url.replaceAll("http://[\\w\\-\\_.]*"+domains.get(i), "http://" + siteConfig.getToRedirect());
                        resp.setStatus(301);
                        resp.setHeader("Location",url);
                        chain.doFilter(request, response);
                        return ;
                }
        	}
        }

        chain.doFilter(request, response);
        

    }

        @Override
        public void destroy() {
                // TODO Auto-generated method stub
                
        }

        @Override
        public void init(FilterConfig arg0) throws ServletException {
                // TODO Auto-generated method stub
                
        }
}